<template>
  <div>
    <el-upload
      list-type="picture-card"
      :on-preview="preview"
      :on-remove="remove"
      :limit="1"
      :file-list="fileList"
      :on-change="change"
      :before-upload="beforeUpload"
      action="#"
      :http-request="upload"
      :class="{disabled: fileCount}"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-progress v-if="showPercent" :percentage="percent" :width="100" />
    <el-dialog title="图片预览" :visible.sync="dialogVisible">
      <img :src="imgSrc" alt="" style="width:100%">
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dialogVisible: false,
      imgSrc: '', // 图片地址
      fileList: [], // 图片显示列表
      currentUid: '', // 当前文件uid
      percent: 0, // 图片上传进度
      showPercent: false // 进度条显示
    }
  },
  computed: {
    fileCount() {
      return this.fileList.length === 1
    }
  },
  methods: {
    // Y预览图片
    preview(file) {
      console.log(file)
      // 设置图片
      this.imgSrc = file.url
      //   弹框显示
      this.dialogVisible = true
    },
    // 删除图片
    remove(file) {
    //   console.log(file)
      this.fileList = this.fileList.filter(item => item.uid !== file.uid) // 把当前删除的文件排除掉
    },
    // 上传
    change(file, filelist) {
    //   console.log(file, filelist)
      //  该方法会执行两次
      // 上传图片腾讯存储桶
      this.showPercent = true
      this.fileList = filelist
      console.log(this.fileList, 'this.fileList')
    },
    beforeUpload(file) {
      // // 图片格式
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      // console.log(file)
      if (!types.includes(file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // 校验文件体积大小5MB 1MB=1024KB   1KB = 1024B
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      this.currentUid = file.uid
      return true
    },
    // 上传
    upload(params) {
      console.log(params, 'params')
      const Cos = require('cos-js-sdk-v5')
      const cos = new Cos({
        SecretId: 'AKIDBA1cwzlHWVCeohJeiV0ECsHPKzNUKtBB',
        SecretKey: 'lFSO3SaR1LOCiywd3B3ey5wXqsd8MJzO'
      })
      //   上傳
      cos.putObject({
        Bucket: '21quanzhan-1303008871', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: params.filename, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData, 'progressData'))
          setTimeout(() => {
            this.percent = progressData.percent * 100
          }, 500)
        }
      }, (err, data) => {
        console.log(data, 'data')
        if (!err && data.statusCode === 200) {
          this.fileList = this.fileList.map(item => {
            if (item.uid === this.currentUid) {
              return { url: 'http://' + data.Location, upload: true }
            }
            return item
          })
          this.showPercent = false
          this.percent = 0
        }
      })
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
     display: none;
}
</style>
